package com.charging.system.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.charging.common.constant.Constants;
import com.charging.common.core.domain.model.LoginUser;
import com.charging.common.utils.ip.IpUtils;
import com.charging.common.wxpay.MyWXPayConfig;
import com.charging.common.wxpay.WXPay;
import com.charging.common.wxpay.WXPayConstants;
import com.charging.common.wxpay.WXPayUtil;
import com.charging.system.domain.KxCard;
import com.charging.system.domain.KxUserInfo;
import com.charging.system.service.IKxCardService;
import com.charging.system.service.IKxUserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.charging.common.annotation.Log;
import com.charging.common.core.controller.BaseController;
import com.charging.common.core.domain.AjaxResult;
import com.charging.common.enums.BusinessType;
import com.charging.system.domain.KxRechargeRecord;
import com.charging.system.service.IKxRechargeRecordService;
import com.charging.common.utils.poi.ExcelUtil;
import com.charging.common.core.page.TableDataInfo;

/**
 * 充值记录Controller
 *
 * @author charging
 * @date 2024-04-19
 */
@RestController
@RequestMapping("/system/recharge_record")
public class KxRechargeRecordController extends BaseController
{
    @Resource
    private IKxRechargeRecordService kxRechargeRecordService;
    @Resource
    private MyWXPayConfig myWXPayConfig;
    @Resource
    private IKxCardService kxCardService;
    @Resource
    private IKxUserInfoService kxUserInfoService;
    /**
     * 查询充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:recharge_record:list')")
    @GetMapping("/list")
    public TableDataInfo list(KxRechargeRecord kxRechargeRecord)
    {
        startPage();
        List<KxRechargeRecord> list = kxRechargeRecordService.selectKxRechargeRecordList(kxRechargeRecord);
        return getDataTable(list);
    }
//    @PreAuthorize("@ss.hasPermi('system:recharge_record:list')")
    @GetMapping("/u_list")
    public TableDataInfo u_list(KxRechargeRecord kxRechargeRecord)
    {
        startPage();
        List<KxRechargeRecord> list = kxRechargeRecordService.selectKxRechargeRecordList(kxRechargeRecord);
        return getDataTable(list);
    }

    /**
     * 导出充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:recharge_record:export')")
    @Log(title = "充值记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KxRechargeRecord kxRechargeRecord)
    {
        List<KxRechargeRecord> list = kxRechargeRecordService.selectKxRechargeRecordList(kxRechargeRecord);
        ExcelUtil<KxRechargeRecord> util = new ExcelUtil<KxRechargeRecord>(KxRechargeRecord.class);
        util.exportExcel(response, list, "充值记录数据");
    }

    /**
     * 获取充值记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:recharge_record:query')")
    @GetMapping(value = "/{rechargeRecordId}")
    public AjaxResult getInfo(@PathVariable("rechargeRecordId") Long rechargeRecordId)
    {
        return success(kxRechargeRecordService.selectKxRechargeRecordByRechargeRecordId(rechargeRecordId));
    }

    /**
     * 新增充值记录
     */
    @PreAuthorize("@ss.hasPermi('system:recharge_record:add')")
    @Log(title = "充值记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KxRechargeRecord kxRechargeRecord)
    {
        return toAjax(kxRechargeRecordService.insertKxRechargeRecord(kxRechargeRecord));
    }

    /**
     * 修改充值记录
     */
    @PreAuthorize("@ss.hasPermi('system:recharge_record:edit')")
    @Log(title = "充值记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KxRechargeRecord kxRechargeRecord)
    {
        return toAjax(kxRechargeRecordService.updateKxRechargeRecord(kxRechargeRecord));
    }

    /**
     * 删除充值记录
     */
    @PreAuthorize("@ss.hasPermi('system:recharge_record:remove')")
    @Log(title = "充值记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{rechargeRecordIds}")
    public AjaxResult remove(@PathVariable Long[] rechargeRecordIds)
    {
        return toAjax(kxRechargeRecordService.deleteKxRechargeRecordByRechargeRecordIds(rechargeRecordIds));
    }


    /**
     * 发起微信支付
     * @return
     */
    @PostMapping("/goRecharge")
    public AjaxResult goRecharge(BigDecimal rechargePrice, BigDecimal givePrice, String cardNo, HttpServletRequest request){
        try{
            WXPay wxpay = new WXPay(myWXPayConfig);
            LoginUser account = getLoginUser();
            KxUserInfo kxUserInfo = kxUserInfoService.selectKxUserInfoByUserId(getUserId());
            // 创建支付订单
            KxRechargeRecord kxRechargeRecord = new KxRechargeRecord();
            String subject = "未知商品";
            if (StringUtils.isNotEmpty(cardNo)){ // 电卡充值
                KxCard kxCard = kxCardService.selectKxCardByCardNo(cardNo);
                kxRechargeRecord.setCardId(kxCard.getCardId());
                kxRechargeRecord.setBalance(rechargePrice);
                kxRechargeRecord.setGive(givePrice);
                // 获取用户当前是使用的充值方案
                kxRechargeRecord.setRechargeSchemeId(100L);
                kxRechargeRecord.setCardNo(kxCard.getCardNo());
                subject = "电卡充值";
            }else{ // 用户充值
                kxRechargeRecord.setUserId(account.getUserId());
                kxRechargeRecord.setBalance(rechargePrice);
                kxRechargeRecord.setGive(givePrice);
                // 获取用户当前是使用的充值方案
                kxRechargeRecord.setRechargeSchemeId(100L);
                kxRechargeRecord.setUserName(kxUserInfo.getUserName());
                subject = "用户充值";
            }
//            kxRechargeRecord.setSplitStatus(MyConstant.SplitStatus.NO);
            kxRechargeRecord.setTranStatus(Constants.TranStatus.NO);
            kxRechargeRecord.setTranType(Constants.TranType.WEIXIN);

            if(kxRechargeRecordService.insertKxRechargeRecord(kxRechargeRecord)> 0){
                String orderNo=String.format("%014d", kxRechargeRecord.getRechargeRecordId());
                Map<String, String> data = new HashMap<String, String>();
                data.put("body", "充电桩-充值"+rechargePrice.toString()+"元"+ (givePrice == null?"无赠送":"赠送"+givePrice.toString())+"元");
                data.put("out_trade_no", Constants.PAY_SIGN+orderNo);
                data.put("device_info", "WEB");
                data.put("fee_type", "CNY");
                data.put("total_fee", rechargePrice.multiply(BigDecimal.valueOf(100)).setScale( 0, BigDecimal.ROUND_DOWN ).toString());
                data.put("spbill_create_ip", IpUtils.getIpAddr(request));
                data.put("notify_url", Constants.kxSystemInfo.getWxPayNotifyUrl());
                data.put("trade_type", "JSAPI");
                data.put("product_id", kxRechargeRecord.getRechargeSchemeId().toString());
                data.put("openid", kxUserInfo.getOpenId());
                Map<String, String> resp = wxpay.unifiedOrder(data);
                logger.info(account.getUsername() + "发起支付请求："+ JSONObject.toJSONString(resp));
                // 微信支付统一订单请求成功
                if("SUCCESS".equals(resp.get("return_code"))&&"SUCCESS".equals(resp.get("result_code"))){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("appId",resp.get("appid"));
                    jsonObject.put("timeStamp", Long.toString(WXPayUtil.getCurrentTimestamp()));
                    jsonObject.put("nonceStr",WXPayUtil.generateNonceStr().toUpperCase());
                    jsonObject.put("package","prepay_id="+resp.get("prepay_id"));
                    jsonObject.put("signType", WXPayConstants.MD5);
                    String singString = "appId="+myWXPayConfig.getAppID()
                            +"&nonceStr="+jsonObject.getString("nonceStr")
                            +"&package="+jsonObject.getString("package")
                            +"&signType="+jsonObject.getString("signType")
                            +"&timeStamp="+jsonObject.getString("timeStamp")
                            +"&key="+myWXPayConfig.getKey();
                    jsonObject.put("paySign",WXPayUtil.MD5(singString));
                    return AjaxResult.success(jsonObject);
                }else {// 微信支付统一订单请求失败
                    return AjaxResult.error("微信支付请求失败");
                }
            }else {
                return AjaxResult.error("创建支付订单失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("微信支付请求失败:"+e.getMessage());
            return AjaxResult.error("微信支付请求失败："+e.getMessage());
        }
    }
}
